﻿using Microsoft.Win32;
using PMSystem.DataAccess;
using PMSystem.DataAccess.DataRepository;
using PMSytem.Windows.App;
using PMSytem.Windows.App.Pages;
using PMSytem.Windows.App.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace PMSytem.Windows.Tests
{
 

    public partial class ViewRecord : ToolWindow
    {
        private us_Photos controlPhotos;
        private List<Images> imageList;
        private List<ImageSource> imageListPrev;
        private int EditRecordid = 0;
        private bool IsEditEnable = false;
        private bool IsnewImageUpload = false;
        private bool IsImageDeleted = false;

        public ViewRecord()
        {
            InitializeComponent();

            DataContext = new RecordImageSource();
            controlPhotos = new us_Photos();
            imageList = new List<Images>();
            imageListPrev = new List<ImageSource>();
        }
        public ViewRecord(int recid)
        {
            InitializeComponent();

            DataContext = new RecordImageSource();
            controlPhotos = new us_Photos();
            imageList = new List<Images>();
            imageListPrev = new List<ImageSource>();
            
            EditRecordid = recid;
            LoadData();
            LoadImages();
            SetPermission();
        }


        private void LoadData()
        {
            using (var repo = new RecordItemRepository())
            {
                var record = repo.GetById(EditRecordid);
                if(record!=null)
                {
                     txtRecordNo.Text= record.RecordNumber;
                     txtTrayNo.Text = record.TrayNumber;
                        txtRackNo.Text= record.RackNumber;
                        txtDescription.Text = record.Description;
                        txtAuthor.Text = record.Author;
                        txtTitle.Text = record.Title;
                }

            }
        }

        private void LoadImages()
        {
            using (var repo = new RecordItemImageRepository())
            {
                var imgList = repo.GetAllByRecordId(EditRecordid);
                if(imgList!=null && imgList.Count>0)
                {
                    foreach (var i in imgList)
                    {
                        ImageSource img = ByteToImage(i.Image);

                        var imageobj = new Images();
                        imageobj.ImageByte = i.Image;
                        imageobj.Image = img;
                        imageList.Add(imageobj);
                        imageListPrev.Add(img);
                    }

                    txtflepath.Text = "";
                    (this.photos.DataContext as RecordImageSource).PhotoList = null;
                    this.photos.DataContext = new RecordImageSource() { PhotoList = imageListPrev };
                }
            }
        }

        private void SetPermission()
        {
            var permission = (LoginUser.IsAdminUser || LoginUser.IsOperatorUser) ? true : false;
            IsEditEnable = permission;
            EnableEdit();
        }
        private void EnableEdit()
        {
            btnSave.Visibility = IsEditEnable? Visibility.Visible:Visibility.Hidden;
            btnUpoad.Visibility = IsEditEnable ? Visibility.Visible : Visibility.Hidden;
            btnBrowse.Visibility = IsEditEnable ? Visibility.Visible : Visibility.Hidden;
            panelUpload.Visibility = IsEditEnable ? Visibility.Visible : Visibility.Hidden;
        }
        
       
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "Select a picture";
            op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";

            if (op.ShowDialog() == true)
            {
                //ImageSource imageSource = new BitmapImage(new Uri(op.FileName));
                ////image.Source = imageSource;

                txtflepath.Text = op.FileName;

                //var imgbytes = File.ReadAllBytes(op.FileName);
                //ImageSource img = ByteToImage(imgbytes);

                //// thumbNail.Source = ByteImageConverter.ByteToImage(imgbytes);

                //var imageobj = new Images();
                //imageobj.ImageByte = imgbytes;
                //imageobj.Image = img;
                //imageList.Add(imageobj);

                ////var temp =  new List<ImageSource>();
                ////ImageSource img = ByteToImage(imgbytes);
                ////temp.Add(img);
                ////temp.Add(img);
                ////temp.Add(img);
                ////temp.Add(img);
                ////temp.Add(img);

                ////imageList.AddRange(imageobj);
                //imageListPrev.Add(img);
            }
        }

        public static ImageSource ByteToImage(byte[] imageData)
        {
            BitmapImage biImg = new BitmapImage();
            MemoryStream ms = new MemoryStream(imageData);
            biImg.BeginInit();
            biImg.StreamSource = ms;
            biImg.EndInit();

            ImageSource imgSrc = biImg as ImageSource;

            return imgSrc;
        }

        private void btnUpoad_Click(object sender, RoutedEventArgs e)
        {
            var filename = txtflepath.Text;
            var imgbytes = File.ReadAllBytes(filename);
            ImageSource img = ByteToImage(imgbytes);

            var imageobj = new Images();
            imageobj.ImageByte = imgbytes;
            imageobj.Image = img;
            imageList.Add(imageobj);
            imageListPrev.Add(img);

            txtflepath.Text = "";
            (this.photos.DataContext as RecordImageSource).PhotoList = null;
            this.photos.DataContext = new RecordImageSource() { PhotoList = imageListPrev };

            IsnewImageUpload = true;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var repo = new RecordItemRepository())
                {
                    var record = repo.GetById(EditRecordid);
                    if (record != null)
                    {

                        record.RecordNumber = txtRecordNo.Text;
                        record.RackNumber = txtRackNo.Text;
                        record.TrayNumber = txtTrayNo.Text;
                        record.Description = txtDescription.Text;
                        record.Author = txtAuthor.Text;
                        record.Title = txtTitle.Text;
                        //record.up = "User 1",
                        //record.CreatedDate = DateTime.Now


                        repo.InsertOrUpdate(record);
                        repo.Save();

                        AuditManager.AddAuditRecord(AuditEntity.UpdateRecord, "update a record item( record id:" + EditRecordid + ")"); 

                        SavePhotos();

                        MessageBox.Show("Successfully update record.", "Edit Record Status",
                                MessageBoxButton.OK,
                                MessageBoxImage.Information,
                                MessageBoxResult.OK,
                                null);

                    }
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
        }

        private void SavePhotos()
        {
            try
            {
                if (imageList != null && imageList.Count > 0)
                {
                    using (var repo = new RecordItemImageRepository())
                    {

                        var imgList = repo.GetAllByRecordId(EditRecordid);
                        if (imgList != null && imgList.Count > 0)
                        {
                            //if (IsnewImageUpload || IsImageDeleted)
                            //{
                                repo.DeleteList(imgList);


                                foreach (var image in imageList)
                                {
                                    try
                                    {
                                        var recordimage = new RecordItemImage()
                                        {
                                            RecordId = EditRecordid,
                                            Image = image.ImageByte,
                                            ImageBinary = image.ImageByte
                                        };
                                        repo.InsertOrUpdate(recordimage);
                                        repo.Save();
                                    }
                                    catch (Exception ex)
                                    {
                                        var errr = ex.Message;
                                    }
                                }
                            //}
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var errr = ex.Message;
            }
        }

    }
}